/**
 *  列表页
 *
 * 作者 admin
 * 日期 2024-08-20 15:49:12
 */
layui.use(['jquery', 'laydate', 'febs', 'form', 'table', 'commonJS', 'validate'], function () {
    var $ = layui.jquery,
        laydate = layui.laydate,
        febs = layui.febs,
        form = layui.form,
        table = layui.table,
        commonJS = layui.commonJS,
        validate = layui.validate,
        $view = $('#febs-hazardExamineAudit'),
        $query = $view.find('#query'),
        $searchForm = $view.find('#hazardExamineAudit-table-form'),
        tableIns;

    form.verify(validate);
    form.render();

    initTable();

    function initTable() {
        tableIns = febs.table.init({
            elem: $view.find('table'),
            id: 'hazardExamineAuditTable',
            url: ctx + 'hazardExamineRecordList',
            where: getQueryParams(),
            limit:Number.MAX_VALUE,
            page:false,
            height: getTableHeight(),
            skin: '',
            cols: [[
                {title: '序号', type: 'numbers',width: 60},
                {field: 'examineId', title: '安全检查主键', hide:true},
                {field: 'examineRecordId', title: '检查记录主键', hide:true},
                {field: 'tenantName', title: '公司名称', minWidth: 260,hide:!hasHeadCompanyRole},
                {field: 'examineNo', title: '检查编号',align:'center', width: 200,event:'baseInfoDetail',templet:function (d) {
                        return '<p style="color:#01aaed;cursor:pointer">'+d.examineNo+'</p>'
                    }
                },
                {field: 'examineTitle', title: '检查主题', minWidth: 500},
                {field: 'examineType', title: '检查类型',align:'center', width: 120, templet: function (d) {
                        var flg = '';
                        switch (d.examineType) {
                            case "1": {
                                flg = '<span>公司检查</span>'
                                break;
                            }
                            case "2": {
                                flg = '<span >部门检查</span>'
                                break;
                            }
                            case "3": {
                                flg = '<span >车间检查</span>'
                                break;
                            }
                            case "4": {
                                flg = '<span >班组检查</span>'
                                break;
                            }
                            case "5": {
                                flg = '<span >项目检查</span>'
                                break;
                            }
                        }
                        return flg;
                    }
                },
                {field: 'startDate', title: '开始时间',align:'center', width: 120},
                {field: 'endDate', title: '结束时间',align:'center', width: 120},
                {field: 'objectId', title: '检查项id',align:'center',hide:true},
                {field: 'objectName', title: '检查项',align:'center', minWidth: 100},
                {field: 'hazardExamineTitle', title: '检查项内容', minWidth: 380,event:'detail',templet:function (d) {
                        if(d.hazardExamineTitle){
                            return '<p style="color:#01aaed;cursor:pointer">'+d.hazardExamineTitle+'</p>'
                        }else{
                            return '';
                        }
                    }
                },
                {field: 'status', title: '检查项状态', width: 120,align:'center', templet: function (d) {
                        var flg = '';
                        switch (d.status) {
                            case "1": {
                                flg = '<span class="layui-badge febs-bg-cyan">待整改指派</span>'
                                break;
                            }
                            case "2": {
                                flg = '<span class="layui-badge febs-bg-green">待整改</span>'
                                break;
                            }
                            case "3": {
                                flg = '<span class="layui-badge febs-bg-geekblue">整改中</span>'
                                break;
                            }
                            case "4": {
                                flg = '<span class="layui-badge febs-bg-orange">待审核</span>'
                                break;
                            }
                            case "5": {
                                flg = '<span class="layui-badge febs-bg-red">审核退回</span>'
                                break;
                            }
                            case "6": {
                                flg = '<span class="layui-badge febs-bg-volcano">已关闭</span>'
                                break;
                            }
                        }
                        return flg;
                    }
                },

                {field: 'rectificationDeadline', title: '整改截至日期',align:'center', width: 120},
                {field: 'examineStatus', title: '安全检查状态',hide: true},
                {title: '操作',align:'center', fixed:'right', toolbar: '#hazardExamineAudit-tool', width: 100}
            ]],
            done: function (res, curr, count) {
                mergeColumn(res);
            },
            // toolbar: '#hazardExamineAudit-toolbar',
            defaultToolbar: []
        });
    }

    function mergeColumn(res) {
        //按字段 合并表格
        var data = res.data;
        if(commonJS.isEmpty(data)){
            return;
        }
        // //console.log("表格数据"+JSON.stringify(data))
        var mergeIndex = 0;//定位需要添加合并属性的行数
        var mark = 1; //这里涉及到简单的运算，mark是计算每次需要合并的格子数
        var columsName = ['tenantName','examineNo','examineTitle','examineType','startDate','endDate','objectName'];//需要合并的列名称
        var columsIndex = [3,4,5,6,7,8,10];//需要合并的列索引值
        for (var k = 0; k < columsName.length; k++) { //这里循环所有要合并的列
            var trArr = $view.find('.layui-table-body').find("tr");//所有行 最大问题出现在此处，获取不到表数据
            for (var i = 1; i < res.data.length; i++) { //这里循环表格当前的数据
                var examineId_before = data[i].examineId;
                var examineId_after = data[i-1].examineId;
                var tdCurArr = trArr.eq(i).find("td").eq(columsIndex[k]);//获取当前行的当前列
                var tdPreArr = trArr.eq(mergeIndex).find("td").eq(columsIndex[k]);//获取相同列的第一列
                if ((examineId_before+data[i][columsName[k]]) === (examineId_after+data[i - 1][columsName[k]]))  { //后一行的值与前一行的值做比较，相同就需要合并
                    mark += 1;
                    tdPreArr.each(function (index,item) {//相同列的第一列增加rowspan属性
                        if(index == 0){
                            $(this).attr("rowspan", mark);
                        }

                    });
                    tdCurArr.each(function (index,item) {//当前行隐藏
                        if(index == 0){
                            $(this).css("display", "none");
                        }
                    });
                } else {
                    mergeIndex = i;
                    mark = 1;//一旦前后两行的值不一样了，那么需要合并的格子数mark就需要重新计算
                }
            }
            mergeIndex = 0;
            mark = 1;

        }
    }

    table.on('sort(hazardExamineAuditTable)', function (obj) {
        tableIns.reload({
            initSort: obj,
            where: $.extend(getQueryParams(), {
                field: obj.field,
                order: obj.type
            }),
            autoSort: true
        });
    });

    function reloadPage(curr) {
        var _curr = $view.find(".layui-laypage-em").next().html();
        if (!!curr) {
            _curr = curr;
        }
        tableIns.reload({where: getQueryParams(), page: {curr: _curr}});
    }

    $query.on('click', function () {
        // reloadPage(1);
        tableIns.reload({where: getQueryParams()});
    });

    table.on('tool(hazardExamineAuditTable)', function (obj) {
        var data = obj.data,
        layEvent = obj.event;
        if (layEvent === 'audit') {
            febs.modal.open('审核', 'hazardExamineAudit/audit/' + data.examineId +'/'+ data.examineRecordId, {
                area: $(window).width() <= 750 ?  ['95%', '85%']:['70%', '85%'],
                btn: ['通过','退回', '取消'],
                yes: function (index, layero) {
                    $('#hazardExamineAudit-edit').find('#submit').trigger('click');
                    return false;
                },
                btn2: function (index, layero) {
                    $('#hazardExamineAudit-edit').find('#return').trigger('click');
                    return false;
                },
                btn3: function () {
                    layer.closeAll();
                },
                data: {
                    tenantId: obj.data.tenantId,
                    examineId:obj.data.examineId,
                    examineRecordId:obj.data.examineRecordId
                },
            });
        }else if(obj.event === 'detail'){
            febs.modal.open('安全检查详情', 'hazardExamineDetail/detail/'+ data.examineId+'/'+ data.examineRecordId, {
                btn: ['关闭'],
                area: $(window).width() <= 750 ? ['95%', '85%']:['80%', '85%'],
                shadeClose:true,
                yes: function (index, layero) {
                    layer.closeAll();
                },
            });
        }else if(obj.event === 'baseInfoDetail'){
            febs.modal.open('安全检查信息', 'hazardExamine/detail/'+data.examineId, {
                btn: ['关闭'],
                area: $(window).width() <= 750 ?  ['95%', '85%']:['80%', '85%'],
                shadeClose:true,
                yes: function (index, layero) {
                    layer.closeAll();
                },
            });
        }
    });

    function getQueryParams() {
        return {
            businessType:'examineAudit',
            tenantId: $searchForm.find("select[name='tenantSelect']").find("option:selected").val(),
            examineNo: $searchForm.find('input[name="examineNo"]').val()?.trim(),
            examineTitle: $searchForm.find('input[name="examineTitle"]').val()?.trim(),
            examineType: $searchForm.find("select[name='examineType']").find("option:selected").val(),
            invalidate_ie_cache: new Date()
        };
    }

    function getTableHeight() {
        return commonJS.calcTableHeight();
    }

    $(window).resize(function () {
        tableIns.reload({height: getTableHeight()});
    });
});